﻿using ApiManage.Models.zyhModels;
using ApiManage.Service.MsSql.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace ApiManage.Service.MsSql.Service
{
    public class SysUserService : BaseService, ISysUserService
    {

        public SysUser GetUser(Expression<Func<SysUser, bool>> where) => _zyhContext.SysUser.FirstOrDefault(where);

        public SysRole GetRole(Expression<Func<SysRole, bool>> where) => _zyhContext.SysRole.FirstOrDefault(where);

        public List<SysMenu> GetMenu(Expression<Func<SysMenu, bool>> where) => _zyhContext.SysMenu.Where(where).ToList();

        public List<SysMenuButton> GetMenuButton(Expression<Func<SysMenuButton, bool>> where) => _zyhContext.SysMenuButton.Where(where).ToList();

        public List<SysMenuColumn> GetMenuColumn(Expression<Func<SysMenuColumn, bool>> where) => _zyhContext.SysMenuColumn.Where(where).ToList();

        public List<SysUser> GetList(Expression<Func<SysUser, bool>> where)
        {
            var users = (from u in _zyhContext.SysUser
                         join r in _zyhContext.SysRole on u.RoleId equals r.RoleId into ur
                         from ure in ur.DefaultIfEmpty()
                         select new SysUser
                         {
                             UserId = u.UserId,
                             LoginName = u.LoginName,
                             UserName = u.UserName,
                             RoleId = u.RoleId,
                             HeadImg = u.HeadImg,
                             Mark = u.Mark,
                             Remark = u.Remark,
                             CreateTime = u.CreateTime,
                             RoleName = ure.RoleName
                         });
            return users.Where(where).ToList();
        }
        public void Insert(SysUser param)
        {
            _zyhContext.SysUser.Add(param);
            _zyhContext.SaveChanges();
        }

        public void Update(SysUser param)
        {
            var user = _zyhContext.SysUser.FirstOrDefault(o => o.UserId == param.UserId);
            user.UserName = param.UserName;
            user.LoginName = param.LoginName;
            user.RoleId = param.RoleId;
            user.Mark = param.Mark;
            _zyhContext.SaveChanges();
        }

        public void Delete(int id)
        {
            var User = _zyhContext.SysUser.FirstOrDefault(o => o.UserId == id);
            User.Mark = 9;
            _zyhContext.SaveChanges();
        }

        public void ResetPwd(int userId, string pwd)
        {
            var User = _zyhContext.SysUser.FirstOrDefault(o => o.UserId == userId);
            User.LoginPwd = pwd;
            _zyhContext.SaveChanges();
        }
    }
}
